// File: BasicBreshenham.java
// Purpose: This class provides an implementation of the Breshenham
//          line draw function with no optimization

import java.awt.*;
import java.awt.image.*;

public class BasicBreshenham implements LineDrawer{
	public void drawLine(BufferedImage bi, int x0, int y0, int x1, int y1){
		int dx,dy;
		int temp;
		
		
		// reduce to half the octant cases by always drawing + in y
		if (y0>y1) {
			temp = y0;
			y0 = y1;
			y1 = temp;
			temp = x0;
			x0 = x1;
			x1 = temp;
		} 
		
		dx = x1-x0;
		dy = y1-y0;
		if (dx>0) {
			if (dx>dy) {
				octant0(bi,x0,y0,dx,dy,1);
			} else {
				octant1(bi,x0,y0,dx,dy,1);
			}
		} else {
			dx = -dx;
			if (dx>dy) {
				octant0(bi,x0,y0,dx,dy,-1);
			} else {
				octant1(bi,x0,y0,dx,dy,-1);
			}	
		}			
	}
	
	private void octant0(BufferedImage bi, int x0, int y0, int dx, int dy,
		int xdirection){
		
		int DeltaYx2;
		int DeltaYx2MinusDeltaXx2;
		int ErrorTerm;
		int pix = 0xffffffff;
		
		// set up initial error term and drawing values
		DeltaYx2 = dy*2;
		DeltaYx2MinusDeltaXx2 = DeltaYx2 - (dx*2);
		ErrorTerm = DeltaYx2 - dx;
		
		// draw loop
		bi.setRGB(x0,y0,pix); // draws a single point
		while ( dx-- > 0){
			// check if we need to advance y
			if (ErrorTerm >=0){
				// advance Y and reset ErrorTerm
				y0++;
				ErrorTerm += DeltaYx2MinusDeltaXx2;	
			} else {
				// add error to ErrorTerm
				ErrorTerm += DeltaYx2;
			}		
			x0 += xdirection;	
			bi.setRGB(x0,y0,pix);
		}			
	}	
	
	private void octant1(BufferedImage bi, int x0, int y0, int dx, int dy,
		int xdirection){
		
		int DeltaXx2;
		int DeltaXx2MinusDeltaYx2;
		int ErrorTerm;
		int pix = 0xffffffff;
		
		// set up initial error term and drawing values
		DeltaXx2 = dx * 2;
		DeltaXx2MinusDeltaYx2 = DeltaXx2 - (dy*2);
		ErrorTerm = DeltaXx2- dy;
		
		// draw loop
		bi.setRGB(x0,y0,pix);
		while ( dy-- > 0) {
			// check if we need to advance x
			if (ErrorTerm >= 0) {
				// advance X and reset ErrorTerm
				x0 += xdirection;
				ErrorTerm += DeltaXx2MinusDeltaYx2;
			} else {
				// add to ErrorTerm
				ErrorTerm += DeltaXx2;
			}
			y0++;
			bi.setRGB(x0,y0,pix);
		}	
	}
	
	
}